package com.day21.test3;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidPooledConnection;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class crud {


    public void insert(int i,String n){

        DruidPooledConnection con=util.getConnection();

        PreparedStatement pstm=null;

        ResultSet rs=null;

        try {
             pstm=con.prepareStatement("INSERT INTO user(id,name) VALUES (?,?)");

            pstm.setInt(1,i);
            pstm.setString(2,n);

            pstm.executeUpdate();
        } catch (SQLException e) {
            e.printStackTrace();
            e.printStackTrace();
            System.out.println("失败");
        }
    }

    public void delete(int i){

        DruidPooledConnection con=util.getConnection();

        PreparedStatement pstm=null;

        ResultSet rs=null;

        try {
            pstm=con.prepareStatement("DELETE FROM user WHERE id=?");

            pstm.setInt(1,i);

            pstm.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
            e.printStackTrace();
            System.out.println("失败");
        }
    }

    public void update(int i,String newname){

        DruidPooledConnection con=util.getConnection();

        PreparedStatement pstm=null;

        ResultSet rs=null;

        try {
            pstm=con.prepareStatement("UPDATE user SET name=? WHERE id=?");

            pstm.setInt(2,i);

            pstm.setString(1,newname);

            pstm.executeUpdate();

        } catch (SQLException e) {
            e.printStackTrace();
            e.printStackTrace();
            System.out.println("失败");
        }
    }


    public String select(int i){

        DruidPooledConnection con=util.getConnection();

        PreparedStatement pstm=null;

        ResultSet rs=null;

        String name="";

        try {
          pstm=con.prepareStatement("SELECT name FROM user WHERE id=?");

          pstm.setInt(1,i);



            rs=pstm.executeQuery();

            while (rs.next()){
              name=rs.getString("name");
            }

        } catch (SQLException e) {
            e.printStackTrace();
            e.printStackTrace();
            System.out.println("失败");
        }finally {
            return name;
        }
    }

}
